from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.db.models import F, Q, Count
from django.http import HttpResponseForbidden
from django.shortcuts import render, get_object_or_404, redirect

from users.models import UserProfile
from .forms import PostForm, CategoryForm, TagForm
from .models import *


@login_required(login_url='/users/login/')
def add_post(request):
    # 获取所有分类和标签
    categories = Category.objects.all()
    tags = Tag.objects.all()

    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.owner = request.user
            post.save()
            return redirect('blog:post_detail', post_id=post.id)
    else:
        form = PostForm()

    # 添加分类和标签数据到上下文
    context = {
        'form': form,
        'category_list': categories,
        'tag_list': tags
    }
    return render(request, 'blog/add_post.html', context)


# 删除文章
@login_required
def delete_post(request, post_id):
    post = get_object_or_404(Post, id=post_id)

    # 只验证是否是作者
    if request.user != post.owner:
        return HttpResponseForbidden("只能删除自己的文章")

    if request.method == 'POST':
        post.delete()
        return redirect('users:user_info')

    return render(request, 'blog/confirm_delete.html', {
        'object': post,
        'type': '文章'
    })


# 删除分类
@login_required
def delete_category(request, category_id):
    category = get_object_or_404(Category, id=category_id)

    if request.method == 'POST':
        category.delete()
        return redirect('users:user_info')

    return render(request, 'blog/confirm_delete.html', {
        'object': category,
        'type': '分类'
    })


# 删除标签
@login_required
def delete_tag(request, tag_id):
    tag = get_object_or_404(Tag, id=tag_id)

    if request.method == 'POST':
        tag.delete()
        return redirect('users:user_info')

    return render(request, 'blog/confirm_delete.html', {
        'object': tag,
        'type': '标签'
    })


@login_required
def add_category(request):
    if request.method == 'POST':
        form = CategoryForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('users:user_info')
    else:
        form = CategoryForm()
    return render(request, 'blog/category_form.html', {'form': form})


@login_required
def add_tag(request):
    if request.method == 'POST':
        form = TagForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('users:user_info')
    else:
        form = TagForm()
    return render(request, 'blog/tag_form.html', {'form': form})


@login_required
def manage_posts(request):
    posts = Post.objects.filter(owner=request.user)
    return render(request, 'blog/manage_posts.html', {'posts': posts})


@login_required
def manage_categories(request):
    categories = Category.objects.all()  # 根据需求调整查询条件
    return render(request, 'blog/manage_categories.html', {'categories': categories})


@login_required
def manage_tags(request):
    tags = Tag.objects.all()  # 根据需求调整查询条件
    return render(request, 'blog/manage_tags.html', {'tags': tags})


def index(request):
    post_list = Post.objects.all()
    categor_list = Category.objects.annotate(num_posts=Count('post')).filter(num_posts__gt=0)

    paginator = Paginator(post_list, 10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    context = {
        'page_obj': page_obj,
        'category_list': categor_list
    }
    return render(request, 'blog/index.html', context)


def category_list(request, category_id):
    category = get_object_or_404(Category, id=category_id)
    # 获取当前分类下的所有文章
    posts = category.post_set.all()
    paginator = Paginator(posts, 2)  # 第二个参数2代表每页显示几个
    page_number = request.GET.get('page')  # http://assas.co/?page=1 (页码)
    page_obj = paginator.get_page(page_number)
    context = {'category': category, 'page_obj': page_obj}
    return render(request, 'blog/list.html', context)


def post_detail(request, post_id):
    post = get_object_or_404(Post, id=post_id)
    prev_post = Post.objects.filter(id__lt=post_id).last()
    next_post = Post.objects.filter(id__gt=post_id).first()
    Post.objects.filter(id=post_id).update(pv=F('pv') + 1)

    try:
        user_profile = post.owner.userprofile
    except UserProfile.DoesNotExist:
        user_profile = None

    context = {
        'post': post,
        'prev_post': prev_post,
        'next_post': next_post,
        'user_profile': user_profile,
    }
    return render(request, 'blog/detail.html', context)


def search(request):
    """ 搜索视图 """
    keyword = request.GET.get('keyword')
    # 没有搜索默认显示所有文章
    if not keyword:
        post_list = Post.objects.all()
    else:
        # 包含查询的方法，用Q对象来组合复杂查询，title__icontains 他两个之间用的是双下划线（__）链接
        post_list = Post.objects.filter(
            Q(title__icontains=keyword) | Q(desc__icontains=keyword) | Q(content__icontains=keyword))
    paginator = Paginator(post_list, 2)  # 第二个参数2代表每页显示几个
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    context = {
        'page_obj': page_obj
    }
    return render(request, 'blog/index.html', context)


def archives(request, year, month):
    # 文章归档列表页
    post_list = Post.objects.filter(add_date__year=year, add_date__month=month)
    paginator = Paginator(post_list, 5)  # 第二个参数2代表每页显示几个
    page_number = request.GET.get('page')  # http://assas.co/?page=1 (页码)
    page_obj = paginator.get_page(page_number)
    context = {'page_obj': page_obj, 'year': year, 'month': month,'post_list': page_obj.object_list}
    return render(request, 'blog/archives_list.html', context)


def author_detail(request, user_id):
    # 获取用户对象
    user = get_object_or_404(User, id=user_id)
    # 获取用户资料
    try:
        user_profile = user.userprofile
    except UserProfile.DoesNotExist:
        user_profile = None

    # 获取用户所有文章
    post_list = Post.objects.filter(owner=user).order_by('-add_date')
    paginator = Paginator(post_list, 10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    context = {
        'author': user,
        'user_profile': user_profile,
        'page_obj': page_obj,
    }
    return render(request, 'blog/author_detail.html', context)